<template>
  <div class="business-application-form">
    <!-- 头部 -->
    <div class="header">
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <h3>{{ isEdit ? '修改开店申请' : '开店申请' }}</h3>
      <div class="header-placeholder"></div>
    </div>

    <!-- 表单内容 -->
    <div class="content">
      <div class="form-section">
        <!-- 店铺名称 -->
        <div class="form-item">
          <label>店铺名称 <span class="required">*</span></label>
          <input type="text" v-model="formData.businessName" placeholder="请输入店铺名称" maxlength="50">
        </div>

        <!-- 店铺地址 -->
        <div class="form-item">
          <label>店铺地址 <span class="required">*</span></label>
          <input type="text" v-model="formData.businessAddress" placeholder="请输入详细地址">
        </div>

        <!-- 店铺描述 -->
        <div class="form-item">
          <label>店铺描述 <span class="required">*</span></label>
          <textarea v-model="formData.businessDescription" placeholder="请输入店铺描述" rows="3" maxlength="500"></textarea>
        </div>

        <!-- 店铺图片 -->
        <div class="form-item">
          <label>店铺图片</label>
          <div class="upload-area" @click="uploadBusinessImage">
            <i class="fas fa-image"></i>
            <p>点击上传店铺图片</p>
            <small>支持JPG、PNG格式，大小不超过5MB</small>
          </div>
        </div>

        <!-- 订单类型 -->
        <div class="form-item">
          <label>订单类型</label>
          <select v-model="formData.orderTypeId">
            <option value="">请选择订单类型</option>
            <option value="1">外卖</option>
            <option value="2">堂食</option>
            <option value="3">外卖+堂食</option>
          </select>
        </div>

        <!-- 起送价 -->
        <div class="form-item">
          <label>起送价 (元)</label>
          <input type="number" v-model="formData.startPrice" placeholder="0.00" step="0.01" min="0">
        </div>

        <!-- 配送费 -->
        <div class="form-item">
          <label>配送费 (元)</label>
          <input type="number" v-model="formData.deliveryPrice" placeholder="0.00" step="0.01" min="0">
        </div>

        <!-- 联系信息 -->
        <div class="form-item">
          <label>联系信息 <span class="required">*</span></label>
          <input type="text" v-model="formData.contactInfo" placeholder="请输入联系电话或联系方式">
        </div>

        <!-- 身份证正面 -->
        <div class="form-item">
          <label>身份证正面 </label>
          <div class="upload-area" @click="uploadIdCardFront">
            <i class="fas fa-id-card"></i>
            <p>点击上传身份证正面</p>
            <small>支持JPG、PNG格式，大小不超过5MB</small>
          </div>
        </div>

        <!-- 身份证反面 -->
        <div class="form-item">
          <label>身份证反面 </label>
          <div class="upload-area" @click="uploadIdCardBack">
            <i class="fas fa-id-card"></i>
            <p>点击上传身份证反面</p>
            <small>支持JPG、PNG格式，大小不超过5MB</small>
          </div>
        </div>

        <!-- 营业执照 -->
        <div class="form-item">
          <label>营业执照 </label>
          <div class="upload-area" @click="uploadBusinessLicense">
            <i class="fas fa-file-contract"></i>
            <p>点击上传营业执照</p>
            <small>支持JPG、PNG格式，大小不超过5MB</small>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitApplication" :disabled="submitting">
        {{ submitting ? '提交中...' : (isEdit ? '更新申请' : '提交申请') }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { applicationAPI } from '@/api/application.js'

const router = useRouter()
const route = useRoute()
const submitting = ref(false)

const isEdit = computed(() => route.params.id !== undefined)

const formData = ref({
  businessName: '',
  businessAddress: '',
  businessDescription: '',
  businessImage: '',
  orderTypeId: '',
  startPrice: 0,
  deliveryPrice: 0,
  contactInfo: '',
  idCardFront: '',
  idCardBack: '',
  businessLicense: ''
})

// 页面加载时，如果是编辑模式，加载申请数据
onMounted(async () => {
  if (isEdit.value) {
    await loadApplicationDetail()
  }
})

// 加载申请详情
const loadApplicationDetail = async () => {
  try {
    const response = await applicationAPI.getApplicationById(route.params.id)
    console.log('完整响应:', response)

    // 简化数据处理逻辑
    let data = null

    // 根据实际响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      // 如果后端返回 { success: true, code: 'OK', data: {...}, message: null }
      data = response.data.data
    } else if (response.data && response.data.id) {
      // 如果后端直接返回申请对象
      data = response.data
    } else {
      // 其他情况
      data = response.data
    }

    console.log('提取的申请详情数据:', data)

    if (data) {
      formData.value = {
        businessName: data.businessName || '',
        businessAddress: data.businessAddress || '',
        businessDescription: data.businessDescription || '',
        businessImage: data.businessImage || '',
        orderTypeId: data.orderTypeId || '',
        startPrice: data.startPrice || 0,
        deliveryPrice: data.deliveryPrice || 0,
        contactInfo: data.contactInfo || '',
        idCardFront: data.idCardFront || '',
        idCardBack: data.idCardBack || '',
        businessLicense: data.businessLicense || ''
      }
      console.log('成功设置表单数据:', formData.value)
    } else {
      console.error('未获取到申请详情数据')
    }
  } catch (error) {
    console.error('获取申请详情失败:', error)
    alert('获取申请详情失败')
  }
}

// 返回上一页
const goBack = () => {
  if (confirm('确定要返回吗？未保存的更改将会丢失。')) {
    router.back()
  }
}

// 上传店铺图片（模拟）
const uploadBusinessImage = () => {
  alert('图片上传功能开发中...')
}

// 上传身份证正面（模拟）
const uploadIdCardFront = () => {
  alert('身份证正面上传功能开发中...')
}

// 上传身份证反面（模拟）
const uploadIdCardBack = () => {
  alert('身份证反面上传功能开发中...')
}

// 上传营业执照（模拟）
const uploadBusinessLicense = () => {
  alert('营业执照上传功能开发中...')
}

// 验证表单
const validateForm = () => {
  if (!formData.value.businessName.trim()) {
    alert('请输入店铺名称')
    return false
  }

  if (!formData.value.businessAddress.trim()) {
    alert('请输入店铺地址')
    return false
  }

  if (!formData.value.businessDescription.trim()) {
    alert('请输入店铺描述')
    return false
  }

  if (!formData.value.contactInfo.trim()) {
    alert('请输入联系信息')
    return false
  }

  // 在实际项目中，这里应该验证图片是否已上传
  // if (!formData.value.idCardFront) {
  //   alert('请上传身份证正面照片')
  //   return false
  // }

  // if (!formData.value.idCardBack) {
  //   alert('请上传身份证反面照片')
  //   return false
  // }

  // if (!formData.value.businessLicense) {
  //   alert('请上传营业执照')
  //   return false
  // }

  return true
}

// 提交申请
const submitApplication = async () => {
  if (!validateForm()) {
    return
  }

  submitting.value = true
  try {
    let response
    if (isEdit.value) {
      // 更新申请
      response = await applicationAPI.updateApplication(route.params.id, formData.value)
    } else {
      // 提交新申请
      response = await applicationAPI.submitApplication(formData.value)
    }

    console.log('提交响应:', response)
    alert(isEdit.value ? '申请更新成功' : '申请提交成功')
    router.push('/businessApplicationList')
  } catch (error) {
    console.error('提交申请失败:', error)
    const errorMessage = error.response?.data?.message || '提交失败，请稍后重试'
    alert('提交失败：' + errorMessage)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.business-application-form {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 4vw;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4vw;
  background: white;
  border-bottom: 1px solid #eee;
}

.header i {
  font-size: 5vw;
  color: #666;
  cursor: pointer;
}

.header h3 {
  font-size: 4.5vw;
  font-weight: normal;
  color: #333;
}

.header-placeholder {
  width: 5vw;
}

.content {
  padding: 4vw;
}

.form-section {
  background: white;
  border-radius: 2vw;
  overflow: hidden;
  margin-bottom: 4vw;
}

.form-item {
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-item label {
  display: block;
  font-size: 4vw;
  color: #333;
  font-weight: 500;
  margin-bottom: 2vw;
}

.required {
  color: #ff4757;
}

.form-item input,
.form-item select,
.form-item textarea {
  width: 100%;
  padding: 3vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  font-size: 4vw;
  outline: none;
  transition: border-color 0.3s;
}

.form-item input:focus,
.form-item select:focus,
.form-item textarea:focus {
  border-color: #ee5a24;
}

.form-item textarea {
  resize: vertical;
  min-height: 20vw;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 1vw;
  padding: 6vw;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #ee5a24;
}

.upload-area i {
  font-size: 8vw;
  color: #999;
  margin-bottom: 2vw;
}

.upload-area p {
  font-size: 4vw;
  color: #666;
  margin-bottom: 1vw;
}

.upload-area small {
  font-size: 3vw;
  color: #999;
}

.submit-btn {
  width: 100%;
  padding: 4vw;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  border-radius: 2vw;
  font-size: 4.5vw;
  cursor: pointer;
  transition: opacity 0.3s;
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.submit-btn:active {
  opacity: 0.8;
}
</style>